package com.letoken.platform.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.app.consumer.FundReleaseConsumer;
import com.letoken.platform.app.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.po.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.web3j.abi.datatypes.Int;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户阿拉丁神灯信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2024-01-23
 */
@Service
@Slf4j
public class AppUserLampServiceImpl extends ServiceImpl<AppUserLampMapper, AppUserLamp> implements AppUserLampService {

    @Autowired
    private AppUserLampService appUserLampService;

    @Autowired
    private AdminLampConfigMapper adminLampConfigMapper;

    @Resource
    AppUserLampMapper appUserLampMapper;

    @Resource
    AppUserTeamPathMapper appUserTeamPathMapper;

    @Resource
    AppUserWalletMapper appUserWalletMapper;

    @Resource
    AppFundV2InfoMapper appFundV2InfoMapper;

    @Autowired
    AppUserWalletService appUserWalletService;


    @Autowired
    AppFundInfoService appFundInfoService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public void addRealPerformance(String[] path, BigDecimal amount) {
        List<AppUserLamp> list = new ArrayList<>();
        for (String inviteID : path) {
            AppUserLamp appUserLamp = appUserLampService.getById(inviteID);
            if (ObjectUtils.isEmpty(appUserLamp)) {
                appUserLamp = new AppUserLamp();
                appUserLamp.setTeamPerformance(amount);
                appUserLamp.setUserId(Integer.valueOf(inviteID));
                appUserLamp.setCreateTime(LocalDateTime.now());
                list.add(appUserLamp);
            } else {
                AppUserLamp appUserLamp1 = new AppUserLamp();
                if (amount.compareTo(BigDecimal.ZERO) < 0 && appUserLamp.getTeamPerformance().add(amount).compareTo(BigDecimal.ZERO) < 0) {
                    appUserLamp1.setTeamPerformance(BigDecimal.ZERO);
                } else {
                    appUserLamp1.setTeamPerformance(appUserLamp.getTeamPerformance().add(amount));
                }
                appUserLamp1.setUserId(Integer.valueOf(inviteID));
                list.add(appUserLamp1);
            }
        }
        appUserLampService.saveOrUpdateBatch(list);
    }

    @Override
    public void updateLamd(String[] path) {
        List<AdminLampConfig> lampConfigList = adminLampConfigMapper.getLampConfigList();
        for (String inviteID : path) {
            Integer userId = Integer.valueOf(inviteID);
            List<AppUserLamp> list = appUserLampMapper.getLampList(userId);
            if (ObjectUtils.isEmpty(list) || list.size() <= 1) continue;
            //取小区中 最大的一个小区做为等级判断
            AppUserLamp appUserLamp = list.get(1);
            AppUserLamp appUserLamp1 = new AppUserLamp();
            Integer level = appUserLampMapper.selectById(userId).getLevel();
            Integer levelOne = 0;
            Integer levelTwo = 0;
            for (AdminLampConfig adminLampConfig : lampConfigList) {
                if (list.size() < 3) {
                    break;
                }

                if (adminLampConfig.getAmoutTeam().compareTo(appUserLamp.getTeamPerformance()) <= 0 && adminLampConfig.getAmoutTeam().compareTo(list.get(2).getTeamPerformance()) <= 0) {
                    levelOne =adminLampConfig.getId();
                    break;
                }

            }

            for (AdminLampConfig adminLampConfig : lampConfigList) {
                if (adminLampConfig.getAmoutTeam().compareTo(appUserLamp.getTeamPerformance()) <= 0) {
                    levelTwo = adminLampConfig.getId();
                    break;
                }
            }

           // log.info("查看等级 用户id+"+inviteID+"levelOne = "+levelOne +"        levelTwo ="+levelTwo);
            if (levelOne>=2 ) {
                appUserLamp1.setLevel(levelOne);
            }else{
                if(levelTwo<3){
                    appUserLamp1.setLevel(levelTwo);
                }else{
                    appUserLamp1.setLevel(2);
                }

            }

            appUserLamp1.setUserId(userId);
            appUserLamp1.setLamp(appUserLampMapper.sumTeamAmount(userId, list.get(0).getUserId()));
            appUserLamp1.updateById();
        }
    }

    /*@Override
    public void updateLamd(String[] path) {
        *//*List<AdminLampConfig> lampConfigList = adminLampConfigMapper.getLampConfigList();
        for (String inviteID : path) {
           Integer userId =  Integer.valueOf(inviteID);
            List<AppUserLamp> list = appUserLampMapper.getLampList(userId);
            if (ObjectUtils.isEmpty(list) || list.size() <= 1) continue;
            //取小区中 最大的一个小区做为等级判断
            AppUserLamp appUserLamp = list.get(1);
            AppUserLamp appUserLamp1 = new AppUserLamp();
            for (AdminLampConfig adminLampConfig : lampConfigList) {
                if(list.size() < 3){
                    appUserLamp1.setLevel(0);
                    break;
                }

                if (adminLampConfig.getAmoutTeam().compareTo(appUserLamp.getTeamPerformance()) <= 0 && adminLampConfig.getAmoutTeam().compareTo(list.get(2).getTeamPerformance()) <= 0) {
                    appUserLamp1.setLevel(adminLampConfig.getId());
                    break;
                }else {
                    appUserLamp1.setLevel(0);
                }
            }
            appUserLamp1.setUserId(userId);
            appUserLamp1.setLamp( appUserLampMapper.sumTeamAmount(userId,list.get(0).getUserId()));
            appUserLamp1.updateById();
        }*//*
        List<AdminLampConfig> lampConfigList = adminLampConfigMapper.getLampConfigList();
        for (String inviteID : path) {
            Integer userId =  Integer.valueOf(inviteID);
            List<AppUserLamp> list = appUserLampMapper.getLampList(userId);
            if (ObjectUtils.isEmpty(list) || list.size() <= 1) continue;
            //取小区中 最大的一个小区做为等级判断
            AppUserLamp appUserLamp = list.get(1);
            AppUserLamp appUserLamp1 = new AppUserLamp();
            for (AdminLampConfig adminLampConfig : lampConfigList) {
                if (adminLampConfig.getAmoutTeam().compareTo(appUserLamp.getTeamPerformance()) <= 0) {
                    appUserLamp1.setLevel(adminLampConfig.getId());
                    break;
                }
            }
            appUserLamp1.setUserId(userId);
            appUserLamp1.setLamp( appUserLampMapper.sumTeamAmount(userId,list.get(0).getUserId()));
            appUserLamp1.updateById();
        }
    }*/

    @Override
    @Transactional
    public void lamd() {
        List<AppUserLamp> list = appUserLampMapper.getLampLevel();
        List<AdminLampConfig> lampConfigList = adminLampConfigMapper.getLampConfigList();
        BigDecimal day = new BigDecimal(30);
        for (AppUserLamp appUserLamp : list) {
            try {
                AdminLampConfig adminLampConfig = lampConfigList.stream().filter(s -> s.getId().equals(appUserLamp.getLevel())).collect(Collectors.toList()).get(0);
                BigDecimal amount = appUserLamp.getLamp().divide(day, 10, RoundingMode.HALF_UP).multiply(adminLampConfig.getIncomeRate());

                AppFundV2Info appFundV2Info = appFundV2InfoMapper.selectBYUserId(appUserLamp.getUserId());
                if (ObjectUtils.isEmpty(appFundV2Info) || appFundV2Info.getRetained().compareTo(BigDecimal.ZERO) == 0)
                    continue;
                if (amount.compareTo(appFundV2Info.getRetained()) > 0) {
                    amount = appFundV2Info.getRetained();
                }

                appUserWalletService.updateWallet(LetokenTokenTypeEnum.LET.getId(), appUserLamp.getUserId(), amount, TokenTransactionTypeEnum.LAMP.getValue(), "");

                AppFundV2Info appFundV2Info1 = appFundInfoService.updateInfo(appUserLamp.getUserId(), amount, BigDecimal.ZERO);
                AppFundV2Detail appFundV2Detail = new AppFundV2Detail();
                appFundV2Detail.setAmount(amount);
                appFundV2Detail.setUserId(appUserLamp.getUserId());
                appFundV2Detail.setCreateTime(LocalDateTime.now());
                appFundV2Detail.setAfterAmount(appFundV2Info1.getRetained());
                appFundV2Detail.setType(7);
                appFundV2Detail.insert();

                fundRelease(appUserLamp.getUserId(), amount);
            } catch (Exception e) {
                log.info("阿拉丁神灯异常用户:{},出错信息:{}", appUserLamp.getUserId(), e.getMessage());
            }

        }
    }


    @Override
    @Transactional
    public void updateLamd(Integer userId, BigDecimal amount) {
        AppUserLamp appUserLamp = appUserLampService.getById(userId);
        if (ObjectUtils.isEmpty(appUserLamp)) {
            appUserLamp = new AppUserLamp();
            appUserLamp.setUserPerformance(amount);
            appUserLamp.setCreateTime(LocalDateTime.now());
            appUserLamp.setUserId(Integer.valueOf(userId));
            appUserLamp.insert();
        } else {
            AppUserLamp appUserLamp1 = new AppUserLamp();
            if (amount.compareTo(BigDecimal.ZERO) < 0 && appUserLamp.getUserPerformance().add(amount).compareTo(BigDecimal.ZERO) < 0) {
                appUserLamp1.setUserPerformance(BigDecimal.ZERO);
            } else {
                appUserLamp1.setUserPerformance(appUserLamp.getUserPerformance().add(amount));
            }
            appUserLamp1.setUserId(Integer.valueOf(userId));
            appUserLamp1.updateById();
        }

        AppUserTeamPath appUserTeamPath = appUserTeamPathMapper.selectById(userId);
        if (appUserTeamPath == null) {
            return;
        }
        if (appUserTeamPath.getInvitePath() == null || appUserTeamPath.getInvitePath().isEmpty() || appUserTeamPath.getInvitePath().equals("0")) {
            return;
        }
        String[] path = appUserTeamPath.getInvitePath().split(",");
        appUserLampService.addRealPerformance(path, amount);
        appUserLampService.updateLamd(path);
    }

    public void fundRelease(Integer userId, BigDecimal amount) {
        FundReleaseConsumer.FundReleaseDto dto = new FundReleaseConsumer.FundReleaseDto();
        dto.setAmount(amount.negate());
        dto.setUserId(userId);
        rabbitTemplate.convertAndSend(FundReleaseConsumer.queue, JSONObject.toJSON(dto).toString());
    }


}
